package com.wang.jmonkey.ca.handler.login.request;

import cn.hutool.core.collection.CollUtil;
import com.wang.jmonkey.ca.model.AuthParam;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author HeJiawang
 * @Date 2021/5/11 10:39
 */
@Component
@Scope("prototype")
public class RequestHandlerManager implements RequestHandler {

    private ApplicationContext context;

    private final List<RequestHandler> handlerList = new ArrayList<RequestHandler>();
    private int index = 0;

    public RequestHandlerManager(ApplicationContext context) {
        this.context = context;
    }

    @PostConstruct
    private void init() {
        Map<String, RequestHandler> handlerMap = context.getBeansOfType(RequestHandler.class);
        if (CollUtil.isEmpty(handlerMap)) return;

        handlerMap.entrySet().forEach(entry -> {
            if (!(entry.getValue() instanceof RequestHandlerManager)) {
                handlerList.add(entry.getValue());
            }
        });
    }

    @Override
    public void handler(HttpServletRequest request, AuthParam authParam, RequestHandler chain) {
        if (index == handlerList.size()) return;

        RequestHandler handler = handlerList.get(index++);
        handler.handler(request, authParam, chain);
    }
}
